package hlhj.com.carviewpad.service

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Message
import com.example.mymvp.log
import com.lzy.okgo.model.Response
import hlhj.com.carviewpad.http.Apis
import hlhj.com.carviewpad.http.CustomAction
import hlhj.com.carviewpad.javabean.AdEvent
import hlhj.com.carviewpad.javabean.MyBaseBean
import hlhj.com.carviewpad.utils.SPHelper
import hlhj.com.carviewpad.utils.TimeUtil
import org.greenrobot.eventbus.EventBus
import java.util.*

/**
 * Created by Never Fear   on 2019\1\17 0017.
Never More....
 */
class UploadService :Service() {
    private var b=false
    private var uploadHandler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            log("游戏","检测时间${TimeUtil.isCurrentInTimeScope(SPHelper.getStimeH(applicationContext),SPHelper.getStimeM(applicationContext),SPHelper.getEtimeH(applicationContext),SPHelper.getEtimeM(applicationContext))}")
            if (TimeUtil.isCurrentInTimeScope(SPHelper.getStimeH(applicationContext),SPHelper.getStimeM(applicationContext),SPHelper.getEtimeH(applicationContext),SPHelper.getEtimeM(applicationContext))){
                if (!b){
                    EventBus.getDefault().post(AdEvent())
                    b=true
                }
            }
            SPHelper.getRecord(applicationContext)?.let {
                log("上传","开始上传==${it}")
                Apis?.upload(SPHelper.getRecord(applicationContext)!!)
                        ?.subscribe(object :CustomAction<Response<MyBaseBean>>(applicationContext){
                            override fun httpSuccess(t: Response<MyBaseBean>) {
                                SPHelper.saveRecord(applicationContext,"[]")
                            }
                        })
                this.sendEmptyMessageDelayed(1,30*60*1000)

            }
        }
    }
    override fun onBind(intent: Intent?): IBinder? {

        return null
    }
    override fun onCreate() {
        super.onCreate()
        log("上传","开始上传?")
        uploadHandler?.sendEmptyMessage(1)
    }
}